package org.andcool.audio.music;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

/**
 * @author Joosun
 * @since 2011-5-28
 */
public class MusicFactory
{
	private static String sAssetBasePath = "";

	public static void setAssetBasePath(final String pAssetBasePath)
	{
		if (pAssetBasePath.endsWith("/") || (pAssetBasePath.length() == 0))
		{
			MusicFactory.sAssetBasePath = pAssetBasePath;
		}
		else
		{
			throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero.");
		}
	}

	public static void reset()
	{
		MusicFactory.setAssetBasePath("");
	}

	public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException
	{
		final MediaPlayer mediaPlayer = new MediaPlayer();

		mediaPlayer.setDataSource(new FileInputStream(pFile).getFD());
		mediaPlayer.prepare();

		final Music music = new Music(pMusicManager, mediaPlayer);
		pMusicManager.add(music);

		return music;
	}

	public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException
	{
		final MediaPlayer mediaPlayer = new MediaPlayer();

		final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath);

		mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
		mediaPlayer.prepare();

		final Music music = new Music(pMusicManager, mediaPlayer);
		pMusicManager.add(music);

		return music;
	}

	public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException
	{
		final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID);
		mediaPlayer.prepare();

		final Music music = new Music(pMusicManager, mediaPlayer);
		pMusicManager.add(music);

		return music;
	}
}